<template>
   <!--面包屑-->
<div style="margin-bottom: 30px">
 <el-breadcrumb separator="/">
   <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
   <el-breadcrumb-item>
     <router-link to="/CargoOwnerList">货主管理</router-link>
   </el-breadcrumb-item>
   <el-breadcrumb-item>货主显示</el-breadcrumb-item>
 </el-breadcrumb></div>
    <!-- 查询 -->
     <el-form :inline="true" :model="forms" class="demo-form-inline">
    <el-form-item label="货主名称:">
      <el-input v-model="forms.CargoOwnerName" placeholder="请输入货主名称" clearable style="width: 150px;"/>
    </el-form-item>
    <el-form-item label="手机号：">
      <el-input v-model="forms.CargoOwnerPhone" placeholder="请输入手机号" clearable style="width: 150px;"/>
    </el-form-item>
    <el-form-item label="驾驶证有效期：">
        <el-date-picker
             v-model="forms.DriverLicenseDate"
            type="date"
           placeholder="请输入驾驶证有效期"
           value-format="YYYY-MM-DD"
       clearable style="width: 180px;"
          />

    </el-form-item>
   
    <el-form-item>
      <el-button type="primary" @click="getListCargoOwner" >查询</el-button>
       <el-button type="primary" @click="reset()">重置</el-button>
    </el-form-item>
  </el-form> 
  <!-- 显示列表 -->
       <el-button type="primary" @click="CreateCargoOwner" >新增</el-button>
           <el-button type="danger" @click="getDelAllCargoOwner" >删除</el-button>
              <el-button type="success" @click="getExport" >导出</el-button>
     <el-table :data="ListCargoOwner" border style="width: 100%" ref="multipleTableRef"  @selection-change="handleSelectionChange">
       <el-table-column type="selection"  width="55" />
        <el-table-column prop="cargoOwnerName" label="货主名称" align="center" />
          <el-table-column prop="cargoOwnerPhone" label="手机号" align="center" />
             <el-table-column prop="cargoOwnerUnitName" label="货主单位" align="center" />
     <el-table-column prop="date" label="联系地址" align="center" >
        <template v-slot="scoped">
<span>{{ scoped.row.startingProvince }}
    {{ scoped.row.startingCity }}
    {{ scoped.row.startingCounty }}
    {{ scoped.row.startingPointAddress }}
</span>
        </template>
     </el-table-column>
       <el-table-column prop="driverLicenseDate" label="驾驶证有效期" align="center" >
                 <template v-slot="scope">
<span>{{ scope.row.driverLicenseDate.replace("T"," ").substring(0,10) }}</span>
    </template>
            </el-table-column>
        <el-table-column prop="driverLicenseImg" label="驾驶证图片" align="center" >
             <template v-slot="scope">
 <div class="table-operation" style="margin-top: 8px;" >
      <el-icon class="operation-icon" ><CircleCheck /></el-icon>
      <span class="operation-text" @click="locks(scope.row.cargoOwnerId)">查看图片</span>
    </div>
    </template>
        </el-table-column>
           <el-table-column prop="cargoOwnerNotes" label="备注" align="center" >
             <template v-slot="scope">
<span v-if="scope.row.cargoOwnerNotes==''">-</span>
    </template>
           </el-table-column>
            <el-table-column prop="createdDate" label="创建时间" align="center" >
                 <template v-slot="scope">
<span>{{ scope.row.createdDate.replace("T"," ").substring(0,19) }}</span>
    </template>
            </el-table-column>
             <el-table-column prop="date" label="操作" align="center">
  <template v-slot="scope">
    <!-- 编辑操作 -->
    <div class="table-operation" >
      <el-icon class="operation-icon"><EditPen /></el-icon>
      <span class="operation-text" @click="edit(scope.row.cargoOwnerId)">编辑</span>
    </div>
 
    <!-- 删除操作 -->
    <div class="table-operation" style="margin-top: 8px;" >
      <el-icon class="operation-icon"><CloseBold /></el-icon>
      <span class="operation-text" @click="del(scope.row.cargoOwnerId)">删除</span>
    </div>
 
    <!-- 查看操作 -->
    <div class="table-operation" style="margin-top: 8px;" >
      <el-icon class="operation-icon"><CircleCheck /></el-icon>
      <span class="operation-text" @click="ed(scope.row.cargoOwnerId)">查看</span>
    </div>
  </template>
  
</el-table-column>
            
  </el-table>
  <!-- 分页 -->
  <div class="demo-pagination-block">

    <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[3, 6, 9, 11]"
        style="float: right;"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <!-- 查看图片 -->
   <div>
    <el-dialog
    v-model="dialogVisible"
    title="驾驶证照片"
    width="500"
  >

 <img :src="'http://113.44.151.225:8000/bwrite/Pic/'+forml.driverLicenseImg"  style="width: 400px; height: 400px;">
    <template #footer>
      <div class="dialog-footer">
       
        <el-button type="primary" @click="dialogVisible = false">
          关闭
        </el-button> 
      </div>
    </template>
  </el-dialog>
   </div>
    <!-- 查看货主信息 -->
   <div>
    <el-dialog
    v-model="dialogVisible1"
    title="货主信息"
    width="700"
  >
     <el-form ref="ruleFormRef" style="max-width: 600px" :model="formm"  label-width="auto"
        class="demo-ruleForm"  status-icon>
        <el-form-item label="货主姓名：" prop="cargoOwnerName">
            <el-input v-model="formm.cargoOwnerName" placeholder="请输入货主姓名" />
        </el-form-item>
       
        <el-form-item label="手机号:" prop="cargoOwnerPhone">
            <el-input v-model="formm.cargoOwnerPhone" placeholder="请输入手机号" />
        </el-form-item>
       
        <el-form-item label="单位名称:" prop="cargoOwnerUnitName">
            <el-input v-model="formm.cargoOwnerUnitName" placeholder="请输入单位名称" />
        </el-form-item>
       
        <el-form-item label="联系地址:" prop="cargoOwnerAddress">
          <el-select v-model="selectedProvince" @change="handleProvinceChange" placeholder="请选择省份" style="width: 130px;">
          <el-option v-for="item in provinces" :key="item.provinceCode" :label="item.provinceName" :value="item.provinceCode" />
        </el-select>
        <el-select v-model="selectedCity" @change="handleCityChange" placeholder="请选择城市" style="width: 130px;">
          <el-option v-for="item in cities" :key="item.provinceCode" :label="item.provinceName" :value="item.provinceCode" />
        </el-select>
        <el-select v-model="selectedCounty" @change="handleCountyChange" placeholder="请选择区县" style="width: 130px;">
          <el-option v-for="item in counties" :key="item.provinceCode" :label="item.provinceName" :value="item.provinceCode" />
        </el-select>
        </el-form-item>
        <el-form-item label="驾驶证有效期:" prop="driverLicenseDate">
          <el-date-picker
             v-model="formm.driverLicenseDate"
            type="date"
         value-format="YYYY-MM-DD"
           placeholder="请输入驾驶证有效期"
            style="width: 100%"
          />
             
</el-form-item>
   
        <el-form-item label="备注:" prop="cargoOwnerNotes">
            <el-input v-model="formm.cargoOwnerNotes" type="textarea" />
        </el-form-item>
             <el-form-item label="驾驶证照片:" prop="driverLicenseImg">
            <el-upload
    class="avatar-uploader"
    action="http://113.44.151.225:8000/bwrite/api/CargoOwner/GetPicName"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
  >
    <img v-if="formm.driverLicenseImg" :src="'http://113.44.151.225:8000/bwrite/Pic/'+formm.driverLicenseImg" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>

        </el-form-item>
        
    </el-form>
    <template #footer>
      <div class="dialog-footer">
       
        <el-button type="primary" @click="dialogVisible1 = false">
          关闭
        </el-button> 
      </div>
    </template>
  </el-dialog>
   </div>
</template>
<script setup lang="ts">
//查看图片
const dialogVisible = ref(false)
const forml = reactive({
    driverLicenseImg:""
})
const locks = (id:number) => {
    axios.get("bwrite/api/CargoOwner/GetCargoOwnerBy?CargoOwnerId=" + id).then(ter => {
    forml.driverLicenseImg = ter.data.data.driverLicenseImg
    })
   dialogVisible.value = true
}
//查看信息
const dialogVisible1 = ref(false)
//图片上传
import { Plus } from '@element-plus/icons-vue'
const handleAvatarSuccess = (val:any) => {
    formm.driverLicenseImg = val
}

//地址
//起点
interface provinc {
    provinceCode: any
    provinceName: any
    cities: any
}
interface citi {
    provinceCode: any
    provinceName: any
    cities: any
}
interface counti {
    provinceCode: any
    provinceName: any
    cities: any
}
const provinces = ref<provinc[]>([])
const cities = ref<citi[]>([])
const counties = ref<counti[]>([])
const selectedProvince = ref("")
const selectedCity = ref("")
const selectedCounty = ref("")

// 处理省份变化
const handleProvinceChange = () => {
    const province = provinces.value.find(p => p.provinceCode === selectedProvince.value);
    if (province) {
        cities.value = province.cities;  // 更新城市列表
        selectedCity.value = '';
        selectedCounty.value = '';
        counties.value = [];
        formm.startingProvince = province.provinceName; // 设置选中的省份名称
    }
}

// 处理城市变化
const handleCityChange = () => {
    const city = cities.value.find(c => c.provinceCode === selectedCity.value);
    if (city) {
        counties.value = city.cities;  // 更新县列表
        selectedCounty.value = '';
        formm.startingCity = city.provinceName; // 设置选中的城市名称
    }
}

// 处理县变化
const handleCountyChange = () => {
    const county = counties.value.find(c => c.provinceCode === selectedCounty.value);
    if (county) {
        formm.startingCounty = county.provinceName; // 设置选中的县名称
    }
}

// 从指定 URL 获取数据
async function fetchData(url: any) {
    try {
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        if (!response.ok) throw new Error('网络响应不正常');
        const data = await response.json();
        return data;
    } catch (error) {
        console.error("数据获取错误:", error);
        ElMessage({
            message: "数据加载失败，请重试。",
            type: "error"
        });
    }
}

// 省改变时的处理函数
const onProvinceChange = () => {
    // 清空城市和区的选择
    selectedCity.value = '';
    selectedCounty.value = '';
    counties.value = [];
    // 获取所选省的城市
    const province = provinces.value.find(p => p.provinceCode === selectedProvince.value);
    cities.value = province ? province.cities : [];
};
// 市改变时的处理函数
const onCityChange = () => {
    // 清空区的选择
    selectedCounty.value = '';
    // 获取所选市的区
    const city = cities.value.find(c => c.provinceCode === selectedCity.value);
    counties.value = city ? city.cities : [];
};
const formm= reactive({
  "cargoOwnerName": "",
  "cargoOwnerPhone": "",
  "cargoOwnerUnitName": "",
  "startingProvince": "",
  "startingCity": "",
  "startingCounty": "",
  "driverLicenseDate": "",
  "cargoOwnerNotes": "",
  "driverLicenseImg": ""
 
})
const ed = (id:number) => {
  axios.get("/bwrite/api/CargoOwner/GetCargoOwnerBy?CargoOwnerId=" + id).then(ter => {

        console.log(ter.data)
        formm.cargoOwnerName = ter.data.data.cargoOwnerName
        formm.cargoOwnerPhone = ter.data.data.cargoOwnerPhone
        formm.cargoOwnerUnitName = ter.data.data.cargoOwnerUnitName
         
    formm.startingProvince = ter.data.data.startingProvince
      selectedProvince.value = ter.data.data.startingProvince
        handleProvinceChange()
        
    formm.startingCity = ter.data.data.startingCity
    selectedCity.value = ter.data.data.startingCity
    handleCityChange()
        
    formm.startingCounty = ter.data.data.startingCounty
     selectedCounty.value = ter.data.data.startingCounty
    handleCountyChange()
        formm.driverLicenseDate = ter.data.data.driverLicenseDate
        formm.cargoOwnerNotes = ter.data.data.cargoOwnerNotes
      formm.driverLicenseImg = ter.data.data.driverLicenseImg
          dialogVisible1.value = true
    })
 
}
//分页
const handleSizeChange = (val: number) => {
    page.PageSize = val
  getListCargoOwner()
}
const handleCurrentChange = (val: number) => {
    page.PageIndex = val  
  getListCargoOwner()
}
//图标
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
    Star,
    CloseBold,
    EditPen,
  CircleCheck
} from '@element-plus/icons-vue'
//多选
const multipleSelection = ref([])//接收id
const multipleSelections = ref([])//接收整条数据
const handleSelectionChange = (val: any) => {
  multipleSelection.value = (val.map(d => d.cargoOwnerId))
    multipleSelections.value = val
   console.log(multipleSelection.value) //多选的id
  
}
const form:any=reactive({
  buttonArray:[]
})
//根据菜单id查询按钮功能权限
const getRoleMenuFun=()=>{
  axios.get('http://47.96.109.219:5202/api/RoleMenuFun/RoleMenuFunId', {
    params: {
      menuId:route.query.id
    }
  }).then(res=>{
    console.log(res);
    form.buttonArray=res.data.data
  }).catch(err=>{
    console.log(err);
    
  })    
}
//组件
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()



//变量
const forms=reactive({
    CargoOwnerName: "",
    CargoOwnerPhone: "",
   DriverLicenseDate:""
    
})
//分页
const page=reactive({
    PageIndex: 1,
    PageSize: 3,
    pageCount: 0,
    totalCount:0
})
//显示货主方法
const ListCargoOwner: any = ref([])
const getListCargoOwner = () => {
    axios.get("/bread/api/CargoOwners/GetCargoOwnerAll", {
        params: {
            CargoOwnerName: forms.CargoOwnerName,
            CargoOwnerPhone: forms.CargoOwnerPhone,
            DriverLicenseDate: forms.DriverLicenseDate,
            PageIndex: page.PageIndex,
            PageSize:page.PageSize,
        }
    }).then(ter => {
        ListCargoOwner.value = ter.data.data.list
     console.log(ter.data)
        page.pageCount = ter.data.data.pageCount
        page.totalCount = ter.data.data.totalCount
      
    
    }).catch(err => {
        console.log(err);
    })
}
//删除（单删）
import { ElMessage, ElMessageBox } from 'element-plus'
const del = (id:number) => {
     ElMessageBox.confirm(
    '确定要删除吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
    .then(() => {
        axios.post("/bwrite/api/CargoOwner/DeleteCargoOwner?CargoOwnerId="+id).then(ter => {
            if (ter.data.code>0) {
                ElMessage.success('删除成功')
            getListCargoOwner()
            }
            else {
            ElMessage.error('删除失败')
        }
      })
    })
    .catch(() => {
    
    })
}
//新增线路跳转
const CreateCargoOwner = () => {
    router.push("/CreatecargoOwner")
}
//删除（多删）
const getDelAllCargoOwner = () => {
    if (multipleSelection.value.length == 0) { 
        ElMessage.error('请选择要删除的线路')
        return
    }
      ElMessageBox.confirm(
    '确定要删除吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
          .then(() => {

              axios.post("/bwrite/api/CargoOwner/DeleteAllCargoOwner", {
            cargoOwnerIds:multipleSelection.value
        }).then(ter => {
            if (ter.data.code>0) {
                ElMessage.success('删除成功')
                 getListCargoOwner()
            }
            else {
            ElMessage.error('删除失败')
        }
      })
    })
    .catch(() => {
    
    })
}
//修改线路
const edit = (id:number) => {
    router.push({
        path: "/UpdateCargoOwner",
        query: {
            id:id
        }
    })
}
//导出货主
//导出
import * as XLSX from 'xlsx';// 导出Excel
const getExport = () => {
  // let url = '/bread/api/CargoOwners/GetExcelName?CargoOwnerName='+forms.CargoOwnerName+'&CargoOwnerPhone='+forms.CargoOwnerPhone+'&DriverLicenseDate='+forms.DriverLicenseDate+'&PageIndex='+page.PageIndex+'&PageSize='+page.PageSize
  // window.location.href = url;
    ElMessageBox.confirm("是否确认导出当前选择的数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
    .then((response) => {
        //  this.selectdata 是复选框的 数据列表
        if (multipleSelections.value.length <= 0) {
            ElMessage.warning('请选择数据！');
            return;
        }
        let tableData = [
            ['序号','货主姓名','手机号', '单位名称', '联系地址', '驾驶证有效日期', '驾驶证照片', "备注", "创建时间"]//导出表头
        ] // 表格表头
        multipleSelections.value.forEach((item, index) => {
            let rowData= []
            //导出内容的字段
            rowData = [
                index + 1, 
                item.cargoOwnerName,
                item.cargoOwnerPhone,
                item.cargoOwnerUnitName,
                item.startingProvince+'-'+item.startingCity+'-'+item.startingCounty,
                item.driverLicenseDate,
                item.driverLicenseImg,
                item.cargoOwnerNotes,
                item.createdDate,
            ]
            tableData.push(rowData)
        })
        let workSheet = XLSX.utils.aoa_to_sheet(tableData);
        let bookNew = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(bookNew, workSheet, '作品名称') // 工作簿名称
        let name = '货主信息表' + timeFormat() + '.xlsx'
        XLSX.writeFile(bookNew, name) // 保存的文件名
    })
}
const timeFormat=()=> {
        let time = new Date();
        let year = time.getFullYear();
        let month = time.getMonth() + 1;
        let date = time.getDate();
        let hours = time.getHours();
        let minutes = time.getMinutes();
        let seconds = time.getSeconds();
        return year + '-' + addZero(month) + '-' + addZero(date) + ' ' + addZero(hours) + ':' + addZero(minutes) + ':' + addZero(seconds);
}
const addZero=(num:any)=> {
    return num < 10 ? '0' + num : num
}
//重置查询条件
const reset = () => {
     forms.CargoOwnerName="",
    forms.CargoOwnerPhone="",
   forms.DriverLicenseDate=""
    getListCargoOwner()
}
//钩子函数
onMounted(async() => {
  getListCargoOwner()
    getRoleMenuFun()
     //获取城市数据
    const res = await fetchData('src/data/city.json'); // 假设这个函数是定义好的，负责获取城市数据
    if (res) {
        provinces.value = res; // 假设 res 是一个包含省的数组
        // 设置选择项
        const province = provinces.value.find(p => p.provinceName === formm.startingProvince);
        if (province) {
            selectedProvince.value = province.provinceCode;
            onProvinceChange(); // 更新城市和区
            const city = cities.value.find(c => c.provinceName === formm.startingCity);
            if (city) {
                selectedCity.value = city.provinceCode;
                onCityChange(); // 更新区
                const county = counties.value.find(c => c.provinceName === formm.startingCounty);
                if (county) {
                    selectedCounty.value = county.provinceCode;
                }
            }
        }
    }
})
</script>
<style scoped>
.table-operation {
  display: flex;
  align-items: center;
}
 
.operation-icon {
  color: blue;
  margin-right: 8px; /* 图标和文本之间的间距 */
}
 
.operation-text {
  color: blue;
  cursor: pointer; /* 鼠标悬停时显示为可点击 */
}
</style>
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
